package com.itheima.service.Impl;

import cn.hutool.core.lang.Snowflake;
import com.itheima.dto.MealDishesDto;
import com.itheima.dto.MealDto;
import com.itheima.mapper.MealDishMapper;
import com.itheima.mapper.MealMapper;
import com.itheima.pojo.Meal;
import com.itheima.service.MealService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MealServiceImpl implements MealService {
    @Resource
    private MealMapper mealMapper;
    @Resource
    private MealDishMapper mealDishMapper;

    @Override
    @Transactional
    public boolean addMeal(MealDto dto) {
        List<MealDishesDto> setmealDishes = dto.getSetmealDishes();
        Meal meal = new Meal();
        String mealId = new Snowflake().nextIdStr();
        meal.setId(mealId);
        BeanUtils.copyProperties(dto, meal);
        boolean res1 = mealMapper.insertMeal(meal) > 0;
        boolean res2 = mealDishMapper.insertMealDish(mealId, setmealDishes) == setmealDishes.size();
        return res1 && res2;
    }

    @Override
    public List<Meal> getMealPage(String name, int page, int pageSize) {
        int index = (page - 1) * pageSize;
        return mealMapper.selectMealPage(name, index, pageSize);
    }

    @Override
    @Transactional
    public boolean modifyMeal(Meal meal) {
        boolean res1 = mealMapper.updateMeal(meal) > 0;
        String mealId = meal.getId();
        mealDishMapper.delByMealIds(mealId);
        List<MealDishesDto> setmealDishes = meal.getSetmealDishes();
        boolean res2 = mealDishMapper.insertMealDish(mealId,setmealDishes) == setmealDishes.size();
        return res1 && res2;
    }

    @Override
    public Meal getMealById(String id) {
        return mealMapper.selectMealById(id);
    }

    @Override
    public boolean modifyStatus(int status, String... ids) {
        return mealMapper.updateStatusById(status, ids) == ids.length;
    }

    @Override
    @Transactional
    public boolean deleteMeal(String[] mealIds) {
        mealDishMapper.delByMealIds(mealIds);
        return mealMapper.deleteMeal(mealIds) == mealIds.length;
    }
}
